package com.manager.plat.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.manager.plat.dao.IConfigBusinessDao;
import com.manager.plat.dao.ILimitCodeDao;
import com.manager.plat.vo.ConfigBusinessVo;
import com.manager.plat.vo.LimitCodeMapVo;
import com.manager.plat.vo.LimitCodeVo;
import com.manager.plat.vo.UserInfoVo;
import com.opensymphony.xwork2.ActionSupport;

public class LimitCodeAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2834501095605184346L;

	private static Logger logger = Logger.getLogger(LimitCodeAction.class);
	
	private ILimitCodeDao limitCodeDao;					//短号码省份管控配置数据接口
	private IConfigBusinessDao configBusinessDao;		//业务信息数据接口
	private List<LimitCodeMapVo> limitCodeMapVoList;	//短号码省份组合信息列表
	private List<ConfigBusinessVo> configBusinessVoList;//业务信息列表
	private LimitCodeVo limitCodeVo;					//业务配置总量信息VO
	private String actionPath;							//操作成功跳转路径
	
	public String getLimitCodeList(){
		/**获得所有短号码分省管控列表*/
		List<LimitCodeVo> limitCodeVoList = limitCodeDao.getLimitCodeList();
		
		if(limitCodeVoList != null && limitCodeVoList.size() > 0){
			/**定义存放短号码省份管控信息VO*/
			Map<String, List<LimitCodeVo>> limitCodeVoListMap = new LinkedHashMap<String, List<LimitCodeVo>>();
			/**从计费信息表中查询所有短号码在各个省份当月已计费*/
			Map<String, Integer> month_used_map = limitCodeDao.getLimitFeeMoney(getCurrMonth());
			
			for(LimitCodeVo limitCodeVo : limitCodeVoList){
				/**获得短号码ID*/
				int sp_code_id = limitCodeVo.getSp_code_id();
				/**获得短号码编号*/
				String sp_code = limitCodeVo.getSp_code();
				/**获得短号码省份*/
				String province = limitCodeVo.getProvince();
				if(month_used_map != null && month_used_map.size() > 0){
					if(month_used_map.get(sp_code + province) != null){
						limitCodeVo.setMonth_used(month_used_map.get(sp_code + province));
					}else{
						limitCodeVo.setMonth_used(0);
					}
				}else{
					limitCodeVo.setMonth_used(0);
				}
				
				/**定义Map中的键*/
				String key = sp_code_id + ":" + sp_code;
				if(limitCodeVoListMap.get(key) != null){
					limitCodeVoListMap.get(key).add(limitCodeVo);
				}else{
					List<LimitCodeVo> limitCodeVoListTemp = new ArrayList<LimitCodeVo>();
					limitCodeVoListTemp.add(limitCodeVo);
					limitCodeVoListMap.put(key, limitCodeVoListTemp);
				}
			}
			
			/**遍历Map 把键值放入一个VO里*/
			if(limitCodeVoListMap != null && limitCodeVoListMap.size() > 0){
				limitCodeMapVoList = new ArrayList<LimitCodeMapVo>();
				for (Map.Entry<String, List<LimitCodeVo>> entry : limitCodeVoListMap.entrySet()) {
					String[] keys = entry.getKey().split(":");
					int sp_code_id = Integer.parseInt(keys[0]);
					String sp_code = keys[1];
					
					/**组装MapVo*/
					LimitCodeMapVo limitCodeMapVo = new LimitCodeMapVo();
					limitCodeMapVo.setSp_code_id(sp_code_id);
					limitCodeMapVo.setSp_code(sp_code);
					limitCodeMapVo.setLimitCodeVoList(entry.getValue());
					
					limitCodeMapVoList.add(limitCodeMapVo);
				}
			}
		}else{
			limitCodeMapVoList = null;
		}
		return SUCCESS;
	}
	
	public String addLimitCode(){
		limitCodeVo = null;
		/**获得所有的有限的短号码列表*/
		configBusinessVoList = configBusinessDao.getConfigBusinessList();
		return SUCCESS;
	}
	
	public String saveLimitCode(){
		HttpServletRequest request = ServletActionContext.getRequest();
		UserInfoVo userInfoVo = (UserInfoVo) request.getAttribute("user");
		
		if(limitCodeVo.getSp_code_id() != 0){
			try {
				limitCodeVo.setProvince(URLDecoder.decode(limitCodeVo.getProvince(), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				logger.error(String.format("保存短号码省份管控信息解码异常:%s", ExceptionUtils.getFullStackTrace(e)));
			}
			
			/**分割所有省份*/
			String[] provinces = limitCodeVo.getProvince().split(":");
			/**定义短号码分省管控列表*/
			List<LimitCodeVo> limitCodeList = new ArrayList<LimitCodeVo>();
			
			if(provinces != null && provinces.length > 0){
				for(String province : provinces){
					LimitCodeVo limitCode = new LimitCodeVo();
					limitCode.setSp_code_id(limitCodeVo.getSp_code_id());
					limitCode.setProvince(province);
					limitCode.setDay_limit(limitCodeVo.getDay_limit());
					limitCode.setMonth_limit(limitCodeVo.getMonth_limit());
					
					limitCodeList.add(limitCode);
				}
			}
			if(limitCodeList != null && limitCodeList.size() > 0){
				/**批量保存省份管控配置信息*/
				int count = limitCodeDao.batchInsertLimitCode(limitCodeList);
				
				ConfigBusinessVo bussinessVo = configBusinessDao.getConfigBusinessById(limitCodeVo.getSp_code_id());
				String sp_code = "";
				if(bussinessVo != null){
					sp_code = bussinessVo.getSp_code();
				}
				if(count > 0){
					logger.info(String.format("[%s]新增短号码[%s]省份[%s]管控配置成功", userInfoVo.getLogin_username(), sp_code, limitCodeVo.getProvince()));
				}else{
					logger.info(String.format("[%s]新增短号码[%s]省份[%s]管控配置失败", userInfoVo.getLogin_username(), sp_code, limitCodeVo.getProvince()));
				}
			}

		}
		
		actionPath = "limitCode/getLimitCodeList.action";
		return SUCCESS;
	}
	
	public String modifyBusinessLimitCode(){
		if(limitCodeVo.getSp_code_id() != 0){
			/**获得所有的有限的短号码列表*/
			configBusinessVoList = configBusinessDao.getConfigBusinessList();
			
			/**根据业务ID获得该短号码下所有的短号码省份管控*/
			List<String> provinceList = limitCodeDao.getBusinessLimitCodeProvinceById(limitCodeVo.getSp_code_id());
			
			String provinces = "";
			if(provinceList != null && provinceList.size() > 0){
				for(String province : provinceList){
					if(!"".equals(province)){
						provinces += province + ",";
					}
				}
				if(!"".equals(provinces)){
					provinces = provinces.substring(0, provinces.length() - 1);
				}
			}
			
			limitCodeVo.setProvince(provinces);
		}
		
		return SUCCESS;
	}
	
	public String updateBusinessLimitCode(){
		HttpServletRequest request = ServletActionContext.getRequest();
		UserInfoVo userInfoVo = (UserInfoVo) request.getAttribute("user");
		if(limitCodeVo.getSp_code_id() != 0){
			int count = limitCodeDao.updateBusinessLimitCode(limitCodeVo);
			if(count > 0){
				logger.info(String.format("[%s]更新短号码[%s]省份管控配置成功", userInfoVo.getLogin_username(),limitCodeVo.getSp_code()));
			}else{
				logger.info(String.format("[%s]更新短号码[%s]省份管控配置失败", userInfoVo.getLogin_username(),limitCodeVo.getSp_code()));
			}
		}
		actionPath = "limitCode/getLimitCodeList.action";
		return SUCCESS;
	}
	
	public String deleteBusinessLimitCode(){
		HttpServletRequest request = ServletActionContext.getRequest();
		UserInfoVo platUser = (UserInfoVo) request.getAttribute("user");
		
		int count = limitCodeDao.deleteBusinessLimitCode(limitCodeVo.getSp_code_id());
		if(count > 0){
			logger.info(String.format("[%s]删除短号码[%s]省份管控信息成功", platUser.getLogin_username(),limitCodeVo.getSp_code()));
		}else{
			logger.info(String.format("[%s]删除短号码[%s]省份管控信息失败", platUser.getLogin_username(),limitCodeVo.getSp_code()));
		}
		actionPath = "limitCode/getLimitCodeList.action";
		return SUCCESS;
	}
	
	public String modifyLimitCode(){
		try {
			/**本地测试*/
//			String province = new String(limitCodeVo.getProvince().getBytes("ISO-8859-1"),"UTF-8");
//			limitCodeVo.setProvince(province);
			/**线上环境*/
			limitCodeVo.setProvince(URLDecoder.decode(limitCodeVo.getProvince(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error(String.format("保存短号码省份管控信息解码异常:%s", ExceptionUtils.getFullStackTrace(e)));
		}
		
		if(limitCodeVo.getSp_code_id() != 0){
			limitCodeVo = limitCodeDao.getLimitCodeBySpCodeIdAndProvince(limitCodeVo.getSp_code_id(), limitCodeVo.getProvince());
		}
		
		/**获得所有的有限的短号码列表*/
		configBusinessVoList = configBusinessDao.getConfigBusinessList();
		
		return SUCCESS;
	}
	
	public String updateLimitCode(){
		HttpServletRequest request = ServletActionContext.getRequest();
		UserInfoVo userInfoVo = (UserInfoVo) request.getAttribute("user");
		
		try {
			limitCodeVo.setProvince(URLDecoder.decode(limitCodeVo.getProvince(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error(String.format("保存省份管控信息解码异常:%s", ExceptionUtils.getFullStackTrace(e)));
		}
		
		if(limitCodeVo.getId() != 0){
			int count  = limitCodeDao.updateLimitCode(limitCodeVo);
			if(count > 0){
				logger.info(String.format("[%s]更新短号码[%s]省份[%s]管控配置成功", userInfoVo.getLogin_username(),limitCodeVo.getSp_code(),limitCodeVo.getProvince()));
			}else{
				logger.info(String.format("[%s]更新短号码[%s]省份[%s]管控配置失败", userInfoVo.getLogin_username(),limitCodeVo.getSp_code(),limitCodeVo.getProvince()));
			}
		}
		actionPath = "limitCode/getLimitCodeList.action";
		return SUCCESS;
	}
	
	public String deleteLimitCode(){
		HttpServletRequest request = ServletActionContext.getRequest();
		UserInfoVo platUser = (UserInfoVo) request.getAttribute("user");
		try {
			limitCodeVo.setProvince(URLDecoder.decode(limitCodeVo.getProvince(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error(String.format("删除长号码省份管控信息解码异常:%s", ExceptionUtils.getFullStackTrace(e)));
		}
		
		int count = limitCodeDao.deleteLimitCode(limitCodeVo.getSp_code_id(), limitCodeVo.getProvince());
		if(count > 0){
			logger.info(String.format("[%s]删除短号码[%s]省份[%s]管控信息成功", platUser.getLogin_username(),limitCodeVo.getSp_code(),limitCodeVo.getProvince()));
		}else{
			logger.info(String.format("[%s]删除短号码[%s]省份[%s]管控信息失败", platUser.getLogin_username(),limitCodeVo.getSp_code(),limitCodeVo.getProvince()));
		}
		actionPath = "limitCode/getLimitCodeList.action";
		return SUCCESS;
	}
	
	private String getCurrMonth(){
		/**获得当前日和月*/
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Calendar calendar = Calendar.getInstance();
		String curr_day = format.format(calendar.getTime());
		String curr_month = curr_day.substring(0,6);
		
		return curr_month;
	}
	
	
	public ILimitCodeDao getLimitCodeDao() {
		return limitCodeDao;
	}
	public void setLimitCodeDao(ILimitCodeDao limitCodeDao) {
		this.limitCodeDao = limitCodeDao;
	}
	public IConfigBusinessDao getConfigBusinessDao() {
		return configBusinessDao;
	}
	public void setConfigBusinessDao(IConfigBusinessDao configBusinessDao) {
		this.configBusinessDao = configBusinessDao;
	}
	public List<LimitCodeMapVo> getLimitCodeMapVoList() {
		return limitCodeMapVoList;
	}
	public void setLimitCodeMapVoList(List<LimitCodeMapVo> limitCodeMapVoList) {
		this.limitCodeMapVoList = limitCodeMapVoList;
	}
	public List<ConfigBusinessVo> getConfigBusinessVoList() {
		return configBusinessVoList;
	}
	public void setConfigBusinessVoList(List<ConfigBusinessVo> configBusinessVoList) {
		this.configBusinessVoList = configBusinessVoList;
	}
	public LimitCodeVo getLimitCodeVo() {
		return limitCodeVo;
	}
	public void setLimitCodeVo(LimitCodeVo limitCodeVo) {
		this.limitCodeVo = limitCodeVo;
	}
	public String getActionPath() {
		return actionPath;
	}
	public void setActionPath(String actionPath) {
		this.actionPath = actionPath;
	}
}
